package org.ysh.core.attachment;

import org.apache.poi.hpsf.CustomProperties;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.ooxml.POIXMLProperties;

import java.util.Date;

import static org.ysh.core.attachment.Word2007AdditionInfoResolver.*;


public class PoiHelper {

    public static void writeCustomInfo(DocumentSummaryInformation dsi,AdditionInfo additionInfo){
        CustomProperties customProperties = dsi.getCustomProperties();
        if(customProperties == null){
            customProperties  = new CustomProperties();
        }
        customProperties.put(CUSTOM_USER,additionInfo.getUserName());
        customProperties.put(CUSTOM_HOST,additionInfo.getHost());
        customProperties.put(CUSTOM_TIME,String.valueOf(additionInfo.getTime().getTime()));
        dsi.setCustomProperties(customProperties);
    }

    public static void writeCustomInfo(POIXMLProperties.CustomProperties customProperties,AdditionInfo additionInfo){
        if(customProperties.contains(CUSTOM_USER)){
            customProperties.getProperty(CUSTOM_USER).setLpstr(additionInfo.getUserName());
        }else{
            customProperties.addProperty(CUSTOM_USER,additionInfo.getUserName());
        }

        if(customProperties.contains(CUSTOM_HOST)){
            customProperties.getProperty(CUSTOM_HOST).setLpstr(additionInfo.getHost());
        }else{
            customProperties.addProperty(CUSTOM_HOST,additionInfo.getHost());
        }

        if(customProperties.contains(CUSTOM_TIME)){
            customProperties.getProperty(CUSTOM_TIME).setLpstr(String.valueOf(additionInfo.getTime().getTime()));
        }else{
            customProperties.addProperty(CUSTOM_TIME,String.valueOf(additionInfo.getTime().getTime()));
        }
    }

    /**
     * 从 07版本的office中读取附件信息
     * @param customProperties
     * @return
     */
    public static AdditionInfo readAdditionInfo(POIXMLProperties.CustomProperties customProperties){
        AdditionInfo additionInfo = new AdditionInfo();
        additionInfo.setUserName(customProperties.getProperty(CUSTOM_USER).getLpwstr());
        additionInfo.setHost(customProperties.getProperty(CUSTOM_HOST).getLpwstr());
        additionInfo.setTime(new Date(Long.valueOf(customProperties.getProperty(CUSTOM_TIME).getLpwstr())));
        return additionInfo;
    }

    /**
     * 从 97-03版本的office中读取附件信息
     * @param dsi
     * @return
     */
    public static AdditionInfo readAdditionInfo(DocumentSummaryInformation dsi){
        CustomProperties customProperties = dsi.getCustomProperties();
        AdditionInfo additionInfo = new AdditionInfo();
        additionInfo.setUserName((String)customProperties.get(CUSTOM_USER));
        additionInfo.setHost((String)customProperties.get(CUSTOM_HOST));
        additionInfo.setTime(new Date(Long.valueOf((String)customProperties.get(CUSTOM_TIME))));
        return additionInfo;
    }

}
